<?php
namespace Beerus\Modules\Designer\Controllers;

use Doraemon\tools\Hhzurl;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\AdmDesignerauthFeedback as mFeedBack;
use Doraemon\service\Designer\AuthFeedBack as sFeedBack;

class AuthFeedBackController extends Controller
{
    const PAGE_SIZE = 20;

    /**
     * 认证咨询列表
     * @param Content $content
     * @param Request $request
     * @return Content
     */
    public function index(Content $content,Request $request)
    {
        $params = $request->all();
        $params['page'] = $params['page'] ?: 1;
        $params['per_page'] = $params['per_page'] ?: self::PAGE_SIZE;
        return $content
            ->header('认证咨询管理')
            ->breadcrumb(
                ['text' => '认证咨询管理列表', 'url' => '/admin/Designer/auth_feedback']
            )
            ->row("<div style='position:fixed;z-index:10000;bottom: 0;left: 0;right: 0;top: 0;text-align: center;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='position: absolute;top:50%;left:50%;transform: translate(-50%,-50%);max-width:600px;max-height:600px;'></div>")
            ->body($this->indexAction($params));
    }

    /**
     * 认证咨询列表展示
     * @param $params
     * @return string
     */
    private function indexAction($params)
    {
        $info = sFeedBack::listing($params);
        $gridModel = new pGridDataModel($info['data'],$info['total'],[
            'perPage' => $params['per_page'],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->tools(function ($tools) {

                $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/Designer/auth_feedback/normalword/edit' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");

            });

            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->dropDown('id', [
                    'content' => '关键词',
                    'uid' => '用户uid',
                    'uname' => '用户昵称'
                ]);
                $filter->equal('status', '类型')->radio(mFeedBack::STATUS);
                $filter->equal('client_type', '系统类型')->radio(mFeedBack::CLIENT_TYPE);
                $filter->equal('app_ver', '系统版本')->select(sFeedBack::listVersionByPhoneType());
                $filter->between('addtime', '时间')->datetime();
            });
            $grid->column('id');
            $grid->column('用户')->display(function(){
                $userArr = $this->user;
                $userStr = '<a target="_blank" href="https://frieza.haohaozhu.me/admin/user/Detail/'.$userArr[0]['uid'].'"><i class="fa fa-user fa-fw"></i>'.$userArr[0]['nick'].'('.$userArr[0]['uid'].')</a>';
                if (!empty($this->user_type)) {
                    $userStr .= "<br />用户身份：" . $this->user_type;
                }
                if (!empty($this->user_quality)) {
                    $userStr .= "<br />用户质量：" . $this->user_quality;
                }

                $str = '';
                if (isset($this->android_phone)) {
                    $str = "<br />手机类型：".$this->android_phone;
                }
                return $userStr."<br \>".'手机型号: '.mFeedBack::CLIENT_TYPE[$this->client_type].' '.$this->client_os_ver."<br />".
                        '应用版本：'.$this->app_ver.$str;
            });
            $grid->cloumn('内容')->display(function(){
                $content = $this->message;
                if ($content['pic_id']) {
                    $str = '<img src="'.$this->img_url.'" class="img" style="height:150px;" />';
                } else {
                    $str = $content['message'];
                }
                return $this->addtime." <br />".$str;
            })->width(500);
            $grid->column('status','状态')->label([
                '未处理' => 'danger',
                '处理中' => 'warning',
                '已回复' => 'success',
            ]);
            $grid->column('','状态')->display(function(){
                $userArr = $this->user;
                return '<a href="/admin/Designer/auth_feedback/'.$userArr[0]['uid'].'" target="_blank"><i class="fa fa-cog fa-spin"></i>处理</a>';
            });
        });

        Admin::script($this->imgScript());

        return $listGrid->render();
    }

    /**
     * 认证咨询处理
     * @param int $uid
     * @param Content $content
     * @return Content
     */
    public function handleFeedback($uid, Content $content)
    {
        return $content
            ->header('认证咨询处理')
            ->breadcrumb(
                [
                    'text' => '认证咨询管理列表',
                    'url'  => '/Designer/auth_feedback'
                ],
                ['text' => "认证咨询处理"]
            )
            ->row(function(Row $row)use($uid) {
                $row->column(6, $this->editActionList($uid));
                $row->column(6, $this->editActionForm($uid));
            });
    }

    /**
     * 认证咨询处理--内容展示
     * @param int $uid
     * @return Grid
     */
    private function editActionList($uid)
    {
        $info = sFeedBack::handleFeedback($uid);
        $gridModel = new pGridDataModel($info['data']);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();
            $grid->tools(function ($tools) {

                // $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/complain/feedback/normalword/list/' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");

            });
            $grid->disablePagination();
            $grid->column('message', '聊天内容')->display(function(){
                return $this->message;
            });
        });

        return $listGrid;
    }

    /**
     * 认证咨询处理--信息编辑
     * @param int $uid
     * @return Form
     */
    private function editActionForm($uid)
    {
        $info = sFeedBack::handleFeedback($uid);
        $word = sFeedBack::getNormalWord();
        $form = new  Form($info);
        $form->display('usermessage','用户');
        $form->textarea('message','消息：');
        $form->select('normalword','常用语：')->options($word)
        ->default('-1')
        ->help('选择常用语后，输入的消息将无效');
        $form->checkbox('status','是否处理')->options([mFeedBack::STATUS_HANDLE=>'处理中']);
        $form->action("/admin/Designer/auth_feedback/$uid");
        return $form;
    }

    public function saveFeedback($uid, Request $request)
    {
        $params = [
            'message'       => trim($request->input('message', '')),
            'normalword'    => $request->input('normalword', ''),
            'status'        =>   $request->input('status', ''),
        ];

        $result = sFeedBack::saveFeedback($uid, $params);

        if ($result['code']) {
            $success = new MessageBag([
                'title' => $result['message'],
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => $result['message'],
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 常用语编辑
     * @param Content $content
     * @return Content
     */
    public function editNormalWord(Content $content)
    {
        $tab = new Tab();
        $tab->add("常用语编辑", $this->editNormalWordAction());
        return $content
            ->header('认证咨询管理')
            ->breadcrumb(
                [
                    'text' => '认证咨询管理列表',
                    'url'  => '/Designer/auth_feedback'
                ],
                ['text' => "常用语编辑"]
            )
            ->body($tab);
    }
    /**
     * 常用语编辑--信息展示
     */
    private function editNormalWordAction()
    {
        $info = sFeedBack::editNormalWord();
        $form = new Form($info);
        $form->textarea('text', '常用语')->help('请用换行隔开每条常用语');
        $form->action('/admin/Designer/auth_feedback/normalword/save');
        return $form->render();
    }

    /**
     * 常用语编辑--信息保存
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveNormalWord(Request $request)
    {
        $text = $request->input('text', '');
        $result = sFeedBack::editNormalWord($text);

        if ($result) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => '操作失败'
            ]));
        }

    }
    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }
}
